# 这个是测试学习中心基线表 基于使用gtsummary进行画图 变化多,样式漂亮 自定义多


library(haven) #用于读取xpt
library(gtsummary)
agerange317dropna <- read.csv('source.csv')

colnames(agerange317dropna)

agerange317dropna$allGroup <-as.factor(agerange317dropna$allGroup)
tbl_summary(agerange317dropna,
            missing = 'no',
            # 通过属性分组
            by = allGroup,
            # 进行设置显示维度
            include = c(RIDAGEYR,Sex,race,FPL,DMDHHSIZ,childhouseholdmembers,familyhomeownershipstatus,HOD050),
            # 批量给变量起别名
            label = list(RIDAGEYR ~ "child age, M (SE)",
                         Sex ~ "child sex",
                         race ~ "child race/ethnicity",
                         FPL ~ "FPL",
                         DMDHHSIZ ~ "no. household members, M (SE)",
                         childhouseholdmembers ~ "no. child household members",
                         familyhomeownershipstatus ~ "family home ownership status",
                         HOD050 ~ "no. household rooms, M (SE)"
            ),
            
            statistic = list(
              # 分别对应数值型和分类变量 后是需要显示表达式
              all_continuous() ~ "{mean}",
              all_categorical() ~ "{n} ({p} ) "
            ),
            digits = all_continuous() ~ 3
)%>%
  #add_n() %>% # 添加非NA观测值个数
  # 这里p值不能用p 根据原文说的是加权得来的 需要用 tbl_svysummay进行 这里除了p值 其他是正确的
  # add_p() %>% # 添加P值
  add_overall() %>%
  #add_significance_stars(hide_se = FALSE,hide_p = TRUE)%>%
  #modify_header(std.error = "**SE**")
  add_ci() %>%
  modify_column_merge(pattern = "{stat_0} ({ci_stat_0})")%>%
  modify_column_merge(pattern = "{stat_1} ({ci_stat_1})")%>%
  modify_column_merge(pattern = "{stat_2} ({ci_stat_2})")%>%
  modify_column_merge(pattern = "{stat_3} ({ci_stat_3})")%>%
  #modify_spanning_header(c("stat_2", "stat_3","stat_4") ~ "**TSE group**")%>%
  modify_header(label = "**characteristic**",all_stat_cols() ~ "**{level}**<br>N = {n} <br> n(% [95% CI]")%>%as_flex_table()%>%flextable::save_as_html(path ='Table1_Result.html')
